package com.gamota.mobi.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.appota.asdk.commons.AccessTokenUtil;
import com.gamota.mobi.AppStoreVnApplication;
import com.gamota.mobi.ListingActivity;
import com.gamota.mobi.ListingActivity.InstalledAppItem;
import com.gamota.mobi.R;
import com.gamota.mobi.event.Event;
import com.gamota.mobi.model.AppStoreVnApplicationInfo;
import com.gamota.mobi.model.ContentItem;
import com.gamota.mobi.view.AlertDialogManager;
import com.gamota.mobi.view.ExpandAnimation;
import com.viewpagerindicator.TitlePageIndicator;
import com.viewpagerindicator.TitlePageIndicator.IndicatorStyle;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.util.AsyncExecutor;
import de.greenrobot.event.util.AsyncExecutor.RunnableEx;

public class Utils {

	private static final long LOW_STORAGE_THRESHOLD = 1024 * 1024 * 10;
	public static final String ALDIKO_SLUG = "aldikodbookdreaderdpremium";
	public static final String MOON_SLUG = "moond-reader-pro-tieng-viet";
	public static final String FBREADER_SLUG = "fbreader";
	public static final String ACV_SLUG = "droiddcomicdviewer";
	
	public static ArrayList<String> pullLinks(String text) {
		ArrayList<String> links = new ArrayList<String>();
		String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(text);
		while(m.find()) {
			String urlStr = m.group();
			if (urlStr.startsWith("(") && urlStr.endsWith(")")){
				urlStr = urlStr.substring(1, urlStr.length() - 1);
			}
			links.add(urlStr);
		}
		return links;
	}
	
	public static String formatNumber(String pattern, int number){
		DecimalFormat myFormatter = new DecimalFormat(pattern);
	    String output = myFormatter.format(number);
	    return output;
	}
	
	public static long calculateDaysToGetGift(int daysToGet){
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.DATE, daysToGet);
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
		String time = sdf.format(c.getTime());
		long unixTime = 0;
		try {
			unixTime = sdf.parse(time).getTime() / 1000L;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return unixTime;
	}
	
	public static void launch(Context context, String packageName){
		try {
			Intent launch = context.getPackageManager().getLaunchIntentForPackage(packageName);
			launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(launch);
		} catch(ActivityNotFoundException e) {
			e.printStackTrace();
		}
		
	}
	
	public static String secondsToString(int seconds) {
		String s = String.format("%02d", seconds / 60) + ":";
		int t = seconds % 60;
		s += t < 10 ? "0" + t : t;
		return s;
	}
	
	public static int getWidthScreen(Context context) {
		DisplayMetrics metric = context.getResources().getDisplayMetrics();
		int width = metric.widthPixels;
		return width;
	}

	public static int getHeightScreen(Context context) {
		DisplayMetrics metric = context.getResources().getDisplayMetrics();
		int height = metric.heightPixels;
		return height;
	}
	
	public static String generateRandomString(int len){
		String str = "0123456789abcdefghijklmnopqrstuvwxyz";
		Random rnd = new Random();
		StringBuilder sb = new StringBuilder(len);
		   for( int i = 0; i < len; i++ ) {
			   sb.append(str.charAt( rnd.nextInt(str.length()))); 
		   }
		return sb.toString();
	}

	public static boolean isInteger(String s) {
		try {
			Integer.parseInt(s);
		} catch (NumberFormatException e) {
			return false;
		}
		return true;
	}

	public static boolean isTablet(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}

	public static String getInstalledPackageNameListStr(Context context) throws NameNotFoundException {
		String returnList = "";
		PackageManager pm = context.getPackageManager();
		List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(0);
		for (int i = 0; i < packs.size(); i++) {
			PackageInfo p = packs.get(i);
			ApplicationInfo ai = pm.getApplicationInfo(p.packageName, 0);
			String appName = p.applicationInfo.loadLabel(
					context.getPackageManager()).toString();
			if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0
					|| appName.equals("AppVIETTEL")
					|| appName.equals("AppMOBI") || appName.equals("AppVINA")
					|| appName.equalsIgnoreCase("appstorevn")
					|| appName.equalsIgnoreCase("senstore")) {
				continue;
			}
			returnList += "\"" + p.applicationInfo.packageName + "\":\""
					+ p.versionName + "|" + p.versionCode + "\",";
		}
		if (returnList.length() > 0) {
			StringBuilder sb = new StringBuilder(returnList.substring(0,
					returnList.length() - 1));
			sb.insert(0, "{");
			sb.insert(returnList.length(), "}");
			return sb.toString();
		} else {
			return "";
		}
	}

	public static String getStaticCurrentStore(Activity context) {
		String currentStore = ((AppStoreVnApplication) context.getApplication()).getCurrentStore();
		if (null == currentStore || currentStore.equals(null)) {
			currentStore = PreferenceManager.getDefaultSharedPreferences(context).getString("d", "home");
		}
		return currentStore;
	}

	public static String getStaticAccessToken(Activity context) {
		String accessToken =null;
		try{
			accessToken = ((AppStoreVnApplication) context.getApplication()).getAccessToken();
		}catch(NullPointerException ex){};
		if (null == accessToken || accessToken.equals(null)) {
			accessToken = AccessTokenUtil.getInstance().init(context).getSavedAccessToken();
			if(accessToken==null || accessToken.equals(null) || accessToken==""){
				accessToken=Constants.DEFIN_TOKEN;
			}
		}
		return accessToken;
	}

	public static boolean getStaticIsLogin(Activity context) {
		boolean isLogin = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Constants.LOGIN, false);
		return isLogin;
	}

	public static boolean getStaticIsRooted(Activity context) {
		boolean isRooted1 = ((AppStoreVnApplication) context.getApplication())
				.isRooted();
		boolean isRooted2 = PreferenceManager.getDefaultSharedPreferences(
				context).getBoolean(Constants.IS_ROOTED, false);
		if ((isRooted1 && isRooted2)) {
			return isRooted1;
		} else {
			return isRooted2;
		}
	}
	
	public static String getStaticCountryCode(Context context){
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		String countryCode = pref.getString(Constants.COUNTRY_CODE, "vn");//fixed for vn
		return countryCode;
	}

	public static boolean isRootedStatic(Context context, boolean isRooted1) {
		boolean isRooted2 = PreferenceManager.getDefaultSharedPreferences(
				context).getBoolean(Constants.IS_ROOTED, false);
		if ((isRooted1 && isRooted2)) {
			return isRooted1;
		} else {
			return isRooted2;
		}
	}

	public static ArrayList<AppStoreVnApplicationInfo> getInstalledApps(Context context, boolean includeSystemApp) throws NameNotFoundException {
		PackageManager pm = context.getPackageManager();
		ArrayList<AppStoreVnApplicationInfo> appList = new ArrayList<AppStoreVnApplicationInfo>();
		List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(0);
		PackageInfo p;
		ApplicationInfo ai;
		for (int i = 0; i < packs.size(); i++) {
			p = packs.get(i);
			ai = pm.getApplicationInfo(p.packageName, 0);
			String appName = p.applicationInfo.loadLabel(context.getPackageManager()).toString();
			if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0 || appName.equalsIgnoreCase("AppStoreVn")) {
				continue;
			}
			AppStoreVnApplicationInfo app = new AppStoreVnApplicationInfo();
			app.setCurrenVersion(p.versionName);
			app.setName(p.applicationInfo.loadLabel(context.getPackageManager()).toString());
			app.setAuthor(p.applicationInfo.packageName);
			Drawable icon = pm.getApplicationIcon(ai);
			app.setIcon(icon);
			app.setPackageName(p.applicationInfo.packageName);
			app.setUpdatable("no");
			appList.add(app);
		}
		return appList;
	}

	public static String getDownloadedContent(List<ContentItem> list) {
		String value = "";
		if (list.size() == 0) {
			return "";
		}
		for (ContentItem item : list) {
			value += "\"" + item.getSlug() + "\":\"" + "T-"
					+ item.getVersionNumber() + "|T-" + item.getVersionNumber()
					+ "\",";
		}
		StringBuilder sb = new StringBuilder(value.substring(0,
				value.length() - 1));
		sb.insert(0, "{");
		sb.insert(value.length(), "}");
		return sb.toString();
	}

	public static String getCarrier(Context context) {
		TelephonyManager tMgr = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String carrier = tMgr.getNetworkOperatorName();
		return carrier;
	}

	public static String getPhone(Context context) {
		TelephonyManager tMgr = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String mPhoneNumber = tMgr.getLine1Number();
		return mPhoneNumber;
	}

	public static String normalizationFileName(String name) {
		String path = name.substring(7, name.length());
		return path.replace("%20", "\\ ");
	}

	public static boolean checkExpired(String endDate) {
		if (endDate.equals("")) {
			return false;
		}
		DateFormat dateFormar = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date now = new Date();
		String str = dateFormar.format(now);
		System.out.println("now=" + str);
		System.out.println("end=" + endDate);
		try {
			return (dateFormar.parse(endDate).before(now));
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		}
	}

	public static void setAppTheme(Resources res, int bgColor, int footerColor, TitlePageIndicator indicator, float density) {
		indicator.setBackgroundColor(res.getColor(bgColor));
		indicator.setFooterColor(res.getColor(footerColor));
		indicator.setFooterLineHeight(1 * density); // 1dp
		indicator.setFooterIndicatorHeight(4 * density); // 3dp
		indicator.setFooterIndicatorStyle(IndicatorStyle.Underline);
		indicator.setTextColor(0xAA000000);
		indicator.setSelectedColor(0xFF000000);
		indicator.setSelectedBold(true);
	}

	public static void setListTheme(Resources res, String currentStore, TitlePageIndicator indicator) {
		final float density = res.getDisplayMetrics().density;
		if (currentStore.equals("apps") || currentStore.equals("games")) {
			Utils.setAppTheme(res, R.color.indicator_bg, R.color.app_indicator, indicator, density);
		} else if (currentStore.equals("books")) {
			Utils.setAppTheme(res, R.color.indicator_bg, R.color.ebook_indicator, indicator, density);
		} else if (currentStore.equals("comics")) {
			Utils.setAppTheme(res, R.color.indicator_bg, R.color.comic_indicator, indicator, density);
		} else if (currentStore.equals("movies")) {
			Utils.setAppTheme(res, R.color.indicator_bg, R.color.film_indicator, indicator, density);
		}
	}

	public static String generateHashMD5(String input) {
		String result = input;
		if (input != null) {
			MessageDigest md;
			try {
				md = MessageDigest.getInstance("MD5");
				md.update(input.getBytes());
				BigInteger hash = new BigInteger(1, md.digest());
				result = hash.toString(16);
				while (result.length() < 32) {
					result = "0" + result;
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(),
				MeasureSpec.AT_MOST);
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
		listView.requestLayout();
	}

	public static Bitmap rotateBitmap(Bitmap original) {
		Matrix matrix = new Matrix();
		matrix.postRotate(90);
		Bitmap rotated = Bitmap.createBitmap(original, 0, 0,
				original.getWidth(), original.getHeight(), matrix, true);
		return rotated;
	}

	public static void copyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	public static String printSize(double size) {
		String value = "";
		double mb=1024*1024;
		if (size > mb && size <= mb*1024) {
			double newSize = size / mb;
			String str = String.valueOf(newSize);
			if (!str.contains(".")) {
				value = str;
			}
			value = str.substring(0, str.indexOf(".") + 2);
			return value + "MB";
		} else if (size > mb*1024) {
			double newSize = size / (mb*1024);
			String str = String.valueOf(newSize);
			if (!str.contains(".")) {
				value = str;
			}
			value = str.substring(0, str.indexOf(".") + 2);
			return value + "GB";
		} else {
			double newSize = size / 1024;
			String str = String.valueOf(newSize);
			if (!str.contains(".")) {
				value = str;
			}
			value = str.substring(0, str.indexOf(".") + 2);
			return value + "KB";
		}
	}

	public static boolean isSdCardWrittenable() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}

	public static long getAvailableStorage() {
		String storageDirectory = null;
		if (isSDCardPresent() && isSdCardWrittenable()) {
			storageDirectory = Environment.getExternalStorageDirectory()
					.toString();
			Log.v(null, "getAvailableStorage. storageDirectory : "
					+ storageDirectory);

			try {
				StatFs stat = new StatFs(storageDirectory);
				long avaliableSize = ((long) stat.getAvailableBlocks() * (long) stat
						.getBlockSize());
				Log.v(null, "getAvailableStorage. avaliableSize : "
						+ avaliableSize);
				return avaliableSize;
			} catch (RuntimeException ex) {
				Log.e(null, "getAvailableStorage - exception. return 0");
				return 0;
			}
		}
		return 0;
	}

	public static long getTotalStorage() {
		String storageDirectory = null;
		if (isSDCardPresent() && isSdCardWrittenable()) {
			storageDirectory = Environment.getExternalStorageDirectory()
					.toString();
			Log.v(null, "getTotalStorage. storageDirectory : "
					+ storageDirectory);

			try {
				StatFs stat = new StatFs(storageDirectory);
				long avaliableSize = ((long) stat.getBlockCount() * (long) stat
						.getBlockSize());
				Log.v(null, "TotalSize : " + avaliableSize);
				return avaliableSize;
			} catch (RuntimeException ex) {
				Log.e(null, "getTotalStorage - exception. return 0");
				return 0;
			}
		}
		return 0;
	}

	public static boolean checkAvailableStorage() {
		if (getAvailableStorage() < LOW_STORAGE_THRESHOLD) {
			return false;
		}

		return true;
	}

	public static boolean isSDCardPresent() {
		return Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
	}

	public static void installAPK(Context context, final String fileName) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.parse(fileName), "application/vnd.android.package-archive");
		intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		intent.setClassName("com.android.packageinstaller","com.android.packageinstaller.PackageInstallerActivity");
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}
	
	public static void uninstallOldVersion(final Activity context){
		if(appInstalledOrNot(context, "com.asvn2013.vn")){
			AlertDialogManager am = new AlertDialogManager(context);
			am.showButtonsDialog(R.string.uninstall_old, new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int pos) {
					// TODO Auto-generated method stub
					switch (pos) {
					case DialogInterface.BUTTON_POSITIVE:
						uninstallAPK(context, "com.asvn2013.vn");
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						context.finish();
						break;
					}
					
				}
			});
		}
	}

	public static void uninstallAPK(Context context, String packageName) {
		Uri packageURI = Uri.parse("package:" + packageName);
		Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
		uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(uninstallIntent);
	}

	public static void installedAppDetails(Context context, String packageName) {
		Uri packageURI = Uri.parse("package:" + packageName);
		Intent uninstallIntent = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
		uninstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(uninstallIntent);
	}

	public static String backupApk(Context context, String packageName) {
		PackageManager pm = context.getPackageManager();
		ApplicationInfo ai;
		try {
			ai = pm.getApplicationInfo(packageName, 0);
			String path = ai.publicSourceDir;
			String fileName = getFileName(path);
			copyfile(path, StorageUtils.BACKUP_ROOT + fileName);
			return fileName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "error";
		}
	}

	private static void copyfile(String srFile, String dtFile) {
		try {
			File f1 = new File(srFile);
			File f2 = new File(dtFile);
			InputStream in = new FileInputStream(f1);

			// For Append the file.
			// OutputStream out = new FileOutputStream(f2,true);

			// For Overwrite the file.
			OutputStream out = new FileOutputStream(f2);

			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
			System.out.println("File copied.");
		} catch (FileNotFoundException ex) {
			System.out
					.println(ex.getMessage() + " in the specified directory.");
			System.exit(0);
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}

	public static int detectNetworkType(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		int type = -1;
		if (null != ni) {
			type = ni.getType();
		}
		return type;
	}

	public static String convertUnixTime(String time) {
		if (time.equals("") || time.equals(null)) {
			return "";
		}
		Date date = new Date(Long.valueOf(time) * 1000);
		SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
		String returnDate = format.format(date);
		return returnDate;
	}
	
	public static String printTime(long time) {
		Date date = new Date(time * 1000);
		SimpleDateFormat format = new SimpleDateFormat("hh:mm a");
		String returnDate = format.format(date);
		return returnDate;
	}

	public static void showConnectionSetting(Context context) {
		final Context ctx = context;
		AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
		builder.setCancelable(true);
		builder.setMessage(R.string.wap_warning);
		builder.setPositiveButton(R.string.setting,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						ctx.startActivity(new Intent(
								Settings.ACTION_WIRELESS_SETTINGS));
					}
				});
		builder.setNegativeButton(R.string.cancel,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						return;
					}
				});
		builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
			public void onCancel(DialogInterface dialog) {
				return;
			}
		});

		builder.show();
	}

	public static void saveDealerKey(Context context, String key) {
		String filename = Constants.DEALER_KEY_FILENAME;
		FileOutputStream fos;
		try {
			fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
			fos.write(key.getBytes());
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static String getDealerKey(Context context) {
		String filename = Constants.DEALER_KEY_FILENAME;
		StringBuffer key = new StringBuffer("");
		FileInputStream fis;
		int ch;
		try {
			fis = context.openFileInput(filename);
			while ((ch = fis.read()) != -1) {
				key.append((char) ch);
			}
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
		return key.toString();
	}

	public static String getVersion(Context context) {
		PackageInfo pInfo = null;
		String version;
		try {
			pInfo = context.getPackageManager().getPackageInfo("com.gamota.mobi", 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		version = pInfo.versionName.trim();
		return version;
	}
	
	public static int getVersionCode(Context context) {
		PackageInfo pInfo = null;
		int version;
		try {
			pInfo = context.getPackageManager().getPackageInfo("com.gamota.mobi", 0);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		version = pInfo.versionCode;
		return version;
	}
	
	public static String getDeviceId(Context con) {
		return ((TelephonyManager) con.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
	}

	public static boolean checkCoolReader(Context context, String path) {
//		PackageManager pm = context.getPackageManager();
//		try {
//			pm.getApplicationInfo("org.coolreader", 0);
//			return true;
//		} catch (NameNotFoundException e) {
//			e.printStackTrace();
//			return false;
//		}
		Intent intent = new Intent(Intent.ACTION_VIEW);
		Log.e("", "path "+path);
	    String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(path)).toString());
	    Log.e("", "extension "+extension);
	    String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
	    Log.e("", "mimetype "+mimetype);
	    if(mimetype==null){
	    	mimetype="application/epub+zip";
	    }
		intent.setDataAndType(Uri.fromFile(new File(path)), mimetype);
		List<ResolveInfo> launchables = context.getPackageManager().queryIntentActivities(intent, PackageManager.GET_INTENT_FILTERS);
		if(launchables.size() > 0){
			return true;
		} else {
			return false;
		}
	}

//	public static boolean checkMoonReader(Context context) {
//		PackageManager pm = context.getPackageManager();
//		try {
//			pm.getApplicationInfo("com.flyersoft.moonreaderp", 0);
//			return true;
//		} catch (NameNotFoundException e) {
//			e.printStackTrace();
//			return false;
//		}
//	}
//
//	public static boolean checkFBReader(Context context) {
//		PackageManager pm = context.getPackageManager();
//		try {
//			pm.getApplicationInfo("org.geometerplus.zlibrary.ui.android", 0);
//			return true;
//		} catch (NameNotFoundException e) {
//			e.printStackTrace();
//			return false;
//		}
//	}
	
	public static boolean checkReader(Context context, String content_type,String path,String mimetype) {
		Log.e("", "mimetype "+mimetype);
		Intent intent = new Intent(Intent.ACTION_VIEW);
	    if(mimetype==null){
	    	if(content_type.equalsIgnoreCase(context.getResources().getString(R.string.books_downloaded))){
	    		mimetype = "application/epub+zip";
	    	}else if(content_type.equalsIgnoreCase(context.getResources().getString(R.string.comics_downloaded))){
	    		mimetype="application/x-acv";
	    	}
	    	
	    }
		intent.setDataAndType(Uri.fromFile(new File(path)), mimetype);
		List<ResolveInfo> launchables = context.getPackageManager().queryIntentActivities(intent, PackageManager.GET_INTENT_FILTERS);
		if(launchables.size() > 0){
			return true;
		} else {
			return false;
		}
	}

	public static boolean checkDroidComicViewer(Context context, String path) {
//		PackageManager pm = context.getPackageManager();
//		try {
//			pm.getApplicationInfo("net.androidcomics.acv", 0);
//			return true;
//		} catch (NameNotFoundException e) {
//			e.printStackTrace();
//			return false;
//		}
		Intent intent = new Intent(Intent.ACTION_VIEW);
		Log.e("", "path "+path);
	    String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(path)).toString());
	    Log.e("", "extension "+extension);
	    String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
	    Log.e("", "mimetype "+mimetype);
	    if(mimetype==null){
	    	mimetype="application/x-acv";
	    }
		intent.setDataAndType(Uri.fromFile(new File(path)), mimetype);
		List<ResolveInfo> launchables = context.getPackageManager().queryIntentActivities(intent, PackageManager.GET_INTENT_FILTERS);
		if(launchables.size() > 0){
			return true;
		} else {
			return false;
		}
	}

	public static boolean checkComicReaderobi(Context context) {
		PackageManager pm = context.getPackageManager();
		try {
			pm.getApplicationInfo("mobi.ComicReaderPlatform", 0);
			return true;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return false;
		}
	}

	public static List<ListingActivity.InstalledAppItem> getInstalledPackageNameList(Context context) throws NameNotFoundException {
		PackageManager pm = context.getPackageManager();
		List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(0);
		InstalledAppItem item;
		PackageInfo p;
		ApplicationInfo ai;
		String appName;
		List<InstalledAppItem> list = new ArrayList<ListingActivity.InstalledAppItem>();
		for (int i = 0; i < packs.size(); i++) {
			p = packs.get(i);
			ai = pm.getApplicationInfo(p.packageName, 0);
			appName = p.applicationInfo.loadLabel(context.getPackageManager()).toString();
			if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0 || appName.equalsIgnoreCase("appstorevn")) {
				continue;
			}
			item = new ListingActivity.InstalledAppItem(p.applicationInfo.packageName, p.versionName);
			list.add(item);
		}
		return list;
	}
	
	public static String getPackageNameList(Context context) throws NameNotFoundException {
		String returnList = "";
		PackageManager pm = context.getPackageManager();
		List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(0);
		for (int i = 0; i < packs.size(); i++) {
			PackageInfo p = packs.get(i);
			ApplicationInfo ai = pm.getApplicationInfo(p.packageName, 0);
			String appName = p.applicationInfo.loadLabel(context.getPackageManager()).toString();
			if ((ai.flags & ApplicationInfo.FLAG_SYSTEM) != 0 || appName.equalsIgnoreCase("appstorevn")) {
				continue;
			}
			returnList += "\"" + p.applicationInfo.packageName + "\":\"" + p.versionName + "|" + p.versionCode + "\",";
		}
		if (returnList.length() > 0) {
			StringBuilder sb = new StringBuilder(returnList.substring(0, returnList.length() - 1));
			sb.insert(0, "{");
			sb.insert(returnList.length(), "}");
			return sb.toString();
		} else {
			return "";
		}
	}

	public static int notificationID() {
		Random randomGenerator = new Random();
		int randomInt = randomGenerator.nextInt(200);
		return randomInt;
	}

	public static String getFileName(String url) {
		String fileName = url.substring(url.lastIndexOf("/") + 1, url.length());
		return fileName;
	}

	public static int measureViewHeight(View expandView, View measureView) {
		try {
			Method m = measureView.getClass().getDeclaredMethod("onMeasure",
					int.class, int.class);
			m.setAccessible(true);
			m.invoke(measureView, MeasureSpec.makeMeasureSpec(
					expandView.getWidth(), MeasureSpec.AT_MOST), MeasureSpec
					.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
		} catch (Exception e) {
			return -1;
		}

		int measuredHeight = measureView.getMeasuredHeight();
		return measuredHeight;
	}

	public static void expandOrCollapse(Context context, View expandView,
			View measureView, float collapsedHeightInDp) {

		DisplayMetrics metrics = context.getResources().getDisplayMetrics();
		int pixels = (int) (metrics.density * collapsedHeightInDp + 0.5f);
		if (expandView.getHeight() < pixels)
			return;

		int measuredHeight = measureViewHeight(expandView, measureView);

		if (measuredHeight < pixels)
			measuredHeight = pixels;

		final int startHeight = expandView.getHeight();
		final int finishHeight = startHeight <= pixels ? measuredHeight
				: pixels;

		expandView.startAnimation(new ExpandAnimation(expandView, startHeight,
				finishHeight));
	}

	public static boolean appInstalledOrNot(Context context, String uri) {
		PackageManager pm = context.getPackageManager();
		boolean appInstalled = false;
		try {
			pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
			appInstalled = true;
		} catch (PackageManager.NameNotFoundException e) {
			appInstalled = false;
		}
		return appInstalled;
	}
	
	public static void deleteFile(final String location){
		final String filePath = location.replace("%20", " ");
		System.err.println("delete file: " + location);
		AsyncExecutor.create().execute(new RunnableEx() {
			@Override
			public void run() throws Exception {
				// TODO Auto-generated method stub
				boolean deleted = false;
				File file = new File(filePath);
				if(file.exists()){
					deleted = file.delete();
				}
				EventBus.getDefault().post(new Event.DeleteFileEvent(deleted));
			}
		});
	}
	
	public static InputStream getKeyStore(Context context){
		  return context.getResources().openRawResource(R.raw.apptoko);
		 }
	public static boolean isPackageExisted(Context context,String targetPackage){
		   PackageManager pm=context.getPackageManager();
		   try {
		    PackageInfo info=pm.getPackageInfo(targetPackage,PackageManager.GET_META_DATA);
		       } catch (NameNotFoundException e) {
//		    	   Log.e("isPackageExisted","FALSE");
		    return false;
		    } 
//		   Log.e("isPackageExisted","TRUE");
		    return true;
		   }
}
